# -*- coding: utf-8 -*-
import sys
import os 

sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../')

import os
import os.path
import json
import uuid
import time
import random
import string
import hashlib
import urllib
import copy

import datetime

from setting import conn

from nomagic.cache import get_user, get_users, update_user, get_doc, get_docs, update_doc

import redis

import logging
logger = logging.getLogger(__name__)

class choice_m:

    def __init__(self):

        pass

    def __del__(self):
        pass

    def add(self, data):

        user = get_user(data['current_user_id'])
        openid = user.get("weixin")
        weixin_name  = user.get("weixin_data").get("nickName")
        weixin_img   = user.get("weixin_data").get("avatarUrl")


        sql = "insert into choice_t (uuid, city, group_id, name, type,\
                user_id, phone_id,  create_time,  username,\
                picture, state) values ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','enable'); commit" %\
                (data['uuid'], data['city'], data['group_id'], data['name'], data['s_type'],\
                data['current_user_id'], data['phone_id'], datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), weixin_name, weixin_img)

        logger.info(sql)
        assert conn.execute_rowcount(sql)

        r = redis.Redis(host='localhost',port=6379,db=0)
        
        for v in data['choice_items']:
            r.sadd(data['uuid'], v)

        pass


    def disable(self, data):

        conn.execute_rowcount("update blog_t set state = 'disable' where id = %s", data['id'])

        pass


    def enable(self, data):

        assert conn.execute_rowcount("update blog_t set state = 'enable' where id = %s", data['id'])

        pass

    def get(self, data):

        sql = "select * from choice_t where group_id = %s and type = %s order by create_time desc" %(data['group_id'], data['type'])
        print sql

        result = conn.query(sql)

        

        return result 

    def get_one(self, data):

        result = conn.query("select * from choice_t where uuid = %s", data['uuid'])

        if len(result) != 0:

            r = redis.Redis(host='localhost',port=6379,db=0)
            result[0]['choice_items'] = list(r.smembers(data['uuid']))

        return result

    def get_my(self, data):

        result = conn.query("select * from choice_t where user_id = %s  order by create_time desc ", data['current_user_id'])

        return result

 
if __name__ == '__main__':

    order_test = order_m()
    order_data = {'group_id': '1', 'order_name': 'test', 's_from':'xx', 's_to':'yy', 'start_time':'2016-10-28 10:00:00', 'phone_id':'132', 'seat_number':'123', \
            's_type':'1', 'username':'mh', 'picture':'123', 'state':'enable'};
    order_test.add_order(order_data)

    order_data = {'group_id':'1'}
    order_result = order_test.get_order(order_data)
    print order_result

